package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.JwtUtil;
import com.itheima.exception.orderException;
import com.itheima.pojo.User;
import com.itheima.service.Impl.UserDetailServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
public class LoginController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserDetailServiceImpl userDetailService;

    @PostMapping("/member/login")
    public Result login(@RequestBody Map<String, String> loginInfo) {
        String telephone = loginInfo.get("telephone");
        String validateCode = loginInfo.get("validateCode");
        // 2. 验证验证码
        String redisCode = (String) redisTemplate.opsForValue().get(telephone);
        if (redisCode == null) {
            return new Result(false, "验证码已过期，请重新获取");
        }
        if (!validateCode.equals(redisCode)) {
            return new Result(false, "验证码错误");
        }

        // 3. 获取或创建用户
        User user = userDetailService.loadUserByTelephone(telephone);
        if (user == null) {
            // 自动注册新用户
            user = new User();
            user.setTelephone(telephone);
            // 生成随机密码（实际不使用）
            user.setPassword(UUID.randomUUID().toString().substring(0, 8));
            userDetailService.register(user);
        }

        // 4. 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", telephone);
        String jwt = JwtUtil.createJWT("wh_study", 300000L, claims);

        // 5. 用户信息存入Redis
        redisTemplate.opsForValue().set("login:" + telephone, user);

        return new Result(true, MessageConstant.LOGIN_SUCCESS, jwt);
    }

    @GetMapping("/validatecode/send4Login")
    public Result send4Login(String telephone) {
        try {
            Integer validateCode = (int)((Math.random()*9+1)*100000);
            log.info("{}的验证码：{}", telephone, validateCode);
            // ★ 使用手机号作为键存储验证码 ★
            redisTemplate.opsForValue().set(telephone, validateCode.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS, validateCode);
        } catch (Exception e) {
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
